package com.tiyende.credit.loop.ui.activity

import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.common.CommonActivity
import com.tiyende.credit.loop.configs.TiyendeApiPath
import com.tiyende.credit.loop.configs.TiyendeApiUrl
import com.tiyende.credit.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.credit.loop.databinding.TiyendeActivityAppSettingBinding
import com.tiyende.credit.loop.event.TiyendeEventPointType
import com.tiyende.credit.loop.request.IHttpCallback
import com.tiyende.credit.loop.ui.dialog.TiyendeUserDataClearDialog
import com.tiyende.credit.loop.utils.helper.TiyendeConfigsHelper
import com.tiyende.credit.loop.utils.helper.TiyendeOrderHelper
import com.tiyende.credit.loop.utils.helper.TiyendeVersionHelper
import com.tiyende.credit.loop.utils.shared.TiyendeSharedHelper
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 16:16
 * @Annotation：设置
 */
class TiyendeAppSettingActivity: CommonActivity() {
    lateinit var binding: TiyendeActivityAppSettingBinding

    private var versionHelper: TiyendeVersionHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功
        } else {
        }
    }

    override fun getTiyendeRootView(): View {
        binding = TiyendeActivityAppSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        setTiyendeBackBtnRes(R.mipmap.tiyende_back_white)
        setTiyendeRightBtnRes(R.mipmap.tiyende_customer_white)
        setTiyendeTextTitle(getString(R.string.tiyende_user_center_app_setting))
        setTiyendeTextTitleColor(Color.parseColor("#FFFFFFFF"))
    }

    override fun initTiyendeListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Setting Page")
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,"Setting Page")
        }

        //版本更新
        binding.btCheckVersionUpdate.setOnClickListener {
            if (!TiyendeConfigsHelper.isTiyendeUpdate()){
                showTiyendeToast(getString(R.string.tiyende_update_no_new_version))
                return@setOnClickListener
            }
            try {
                if (versionHelper == null){
                    versionHelper = TiyendeVersionHelper(activity = this, isMust = true, updateLauncher)
                }
                versionHelper?.startVersionUpdate {  }
            } catch (e: Exception) {
                showTiyendeToast(getString(R.string.tiyende_update_no_new_version))
            }
        }

        //清空用户数据
        binding.btDataClear.setOnClickListener {
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_DATA_CLEAR,"Setting")
            //存在未结清的账单
            if (isUserSettingCheckUncleared()){
                showErrorTipsDialog(getString(R.string.tiyende_app_setting_user_data_clear_error),"Setting Page")
                return@setOnClickListener
            }
            showUserClearDataDialog()
        }

        //退出登录
        binding.btLoginOut.setOnClickListener {
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_USER_LOGINOUT,"")
            //退出登录，需要移除用户保存的信息
            TiyendeSharedHelper.onTiyendeLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(TiyendeLoginActivity::class.java)
            },300)
        }
    }

    override fun loadTiyendeData() {
        binding.btDataClear.visibility = View.GONE
        loadUserClearDataAction(true)

        //是否有新版本
        binding.userSettingNewVersionPoint.visibility = View.GONE
        if (TiyendeConfigsHelper.isTiyendeUpdate()){
            binding.userSettingNewVersionPoint.visibility = View.VISIBLE
        }
    }

    override fun onResume() {
        super.onResume()
        versionHelper?.resume()
    }

    /**
     * 是否存在未结清的账单
     */
    private fun isUserSettingCheckUncleared(): Boolean{
        val orderList = TiyendeOrderHelper.queryTiyendeOrderList()
        if (orderList.size == 0){
            return false
        }
        orderList.forEach {
            val orderStatus = it.optString("orderStatus")
            return when(orderStatus){
                "IN_REVIEW","LENDING","WAIT_REPAY" -> {
                    true
                }
                else -> {
                    false
                }
            }
        }
        return false
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = TiyendeUserDataClearDialog(this,object : TiyendeUserDataClearDialog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                showTiyendeLoading()
                loadUserClearDataAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    private fun loadUserClearDataAction(isShowButton: Boolean){
        val httpUrl = TiyendeApiUrl.getTiyendeHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_USER_DATA_CLEAR_NEW_PATH)
        }
        if (isShowButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hiddenTiyendeLoading()
                if (isShowButton){
                    val obj = data.optJSONObject("obj")
                    if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                        binding.btDataClear.visibility = View.VISIBLE
                    } else {
                        binding.btDataClear.visibility = View.GONE
                    }
                } else {
                    //退出登录，需要移除用户保存的信息
                    TiyendeSharedHelper.onTiyendeLoginOut()
                    onIntent(TiyendeLoginActivity::class.java)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showTiyendeToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hiddenTiyendeLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_USER_SETTING_END)
    }
}